var mongoose = require('mongoose')
var User = mongoose.model('User')
var Comment = mongoose.model('Comment')
var config = require('../../config')
var wechatApi = config.getWechat()
var sign = require('../../libs/util').sign
var Art = require('../api/art')
var koa_request = require('koa-request')

exports.guess = function *(next){
    var data = yield wechatApi.fetchAccessToken()
    var access_token = data.access_token
    var ticketData = yield wechatApi.fetchTicket(access_token)
    var ticket = ticketData.ticket
    var url = this.href
    var params = sign(ticket,url)
    this.body = yield this.render('wechat/game',params)
}
exports.jump = function *(next){
    var movieId = this.params.id
    var redirect = 'http://99287afa.ngrok.io/movie/'+movieId
    var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+config.configOption.wechat.appID+'&redirect_uri='+redirect+
    '&response_type=code&scope=snsapi_base&state='+movieId+'#wechat_redirect' 
    this.redirect(url)
}
exports.find = function *(next){
    var code = this.query.code
    var openUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='+config.configOption.wechat.appID+'&secret='+config.configOption.wechat.appID+'&code='+code+'&grant_type=authorization_code'
    var response = yield koa_request({
        url: openUrl
    })
    
    var body = JSON.parse(response.body)
    var openid = body.openid
    var user = yield User.findOne({openid: openid}).exec()

    if(!user){
        user = new User({
            openid: openid,
            password: 'imoocimooc',
            name: Math.random().toString(36).substr(2)
        })

        user = yield user.save()
    }
    this.session.user = user
    this.state.user = user

    var id = this.params.id
    var data = yield wechatApi.fetchAccessToken()
    var access_token = data.access_token
    var ticketData = yield wechatApi.fetchTicket(access_token)
    var ticket = ticketData.ticket
    var url = this.href
    var params = sign(ticket,url)
    var movie = yield Movie.searchById(id)

    var coments = yield Comment
      .find({movie: id})
      .populate('from', 'name')
      .populate('reply.from reply.to', 'name')
      .exec()

    params.movie = movie
    params.coments = coments
    console.log(params)
    yield this.render('wechat/movie',params)
}
exports.getarticles = function *(next){
    var q = this.query.q

    if (q) {
        var categories = yield Art.searchByCategoty(q)
        var category = categories[0] || {}
        var articles = category.articles || []
        console.log(articles)
        var results = articles.filter(function(item,index){
            return item.isSend
        })

        yield this.render('wechat/articlesByCat', {
          title: q,
          articles: results
        })
    }
      
}